<template>
  <div>
    <el-card>
      <div class="e_title">
        订单统计
        <span>
          <el-check-tag
            class="el-check-tag"
            v-for="(item, i) in options"
            :key="i"
            :checked="currentOptions == item.value"
            @change="selectOption(item.value)"
            >{{ item.text }}</el-check-tag
          >
        </span>
      </div>
      <div id="e_main"></div>
    </el-card>
  </div>
</template>

<script setup>
import * as echarts from "echarts";
import { ref, onMounted, onBeforeUnmount } from "vue";
import { getEchartsDataFn } from "@/api/home.js";
let myChart;

// 设置echarts数据，并进行后端交互数据
const getEchartsData = async () => {
  let option = {
    xAxis: {
      type: "category",
      data: [],
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        data: [],
        type: "bar",
        showBackground: true,
        backgroundStyle: {
          color: "rgba(180,180,180,0.2)",
        },
      },
    ],
  };
  // 调用接口之前显示loading动画
  myChart.showLoading();
  // 获取真实数据
  const res = await getEchartsDataFn(currentOptions.value);
  if (res.msg && res.msg !== "ok") {
    return;
  }
  // 拿到数据之后关闭loading动画
  myChart.hideLoading();
  option.xAxis.data = res.data.x;
  option.series[0].data = res.data.y;
  myChart.setOption(option);
};

// 默认选中近一周
const currentOptions = ref("week");
const options = [
  {
    text: "月",
    value: "month",
  },
  {
    text: "周",
    value: "week",
  },
  {
    text: "天",
    value: "hour",
  },
];
// 修改默认选项
const selectOption = (op) => {
  currentOptions.value = op;
};
onMounted(() => {
  const chartDom = document.getElementById("e_main");
  myChart = echarts.init(chartDom);
  getEchartsData();
  window.addEventListener("resize", function () {
    myChart.resize();
  });
});
onBeforeUnmount(() => {
  // 销毁echarts实例
  if (myChart) {
    echarts.dispose(myChart);
  }
});
</script>

<style lang="less" scoped>
.e_title {
  display: flex;
  border-bottom: 1px solid #dbdbdb;
  line-height: 30px;
  padding-bottom: 10px;
  span {
    margin-left: auto;

    .el-check-tag {
      margin-left: 10px;
    }
  }
}
#e_main {
  height: 100%;
  height: 330px;
}
</style>
